﻿using System;
using System.Web;
using System.Web.UI;
using SocialFront.Entities;
using SocialFront.Providers.Member;

namespace SocialFront.Web.usercontrols.Membership
{
    public partial class MemberSignIn : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MemberSignIn"/> class.
        /// </summary>
        public MemberSignIn()
        {
            //SignOutLinkText = "Sign out";
            LoggedInText = "You're logged in as %%NAME%% - ";
            LogOutOnly = false;
        }

        public bool UseCookiesForAuthentication { get; set; }


        public bool LogOutOnly { private get; set; }

        public string LoggedInText { private get; set; }

        public string SignOutLinkText { private get; set; }

        /// <summary>
        /// Sets the username caption.
        /// </summary>
        /// <value>The username caption.</value>
        public string UsernameCaption
        {
            set
            {
                //if (value.Length > 0 && value.Substring(0, 1) == "#")
                //    // TODO: Create a DirectoryProvider to replace calls to umbraco.library.GetDictionaryItem
                //    LiteralUsername.Text = umbraco.library.GetDictionaryItem(value.Substring(1, value.Length - 1));
                //else
                    LiteralUsername.Text = value;
            }
        }

        /// <summary>
        /// Sets the password caption.
        /// </summary>
        /// <value>The password caption.</value>
        public string PasswordCaption
        {
            set
            {
                //if (value.Length > 0 && value.Substring(0, 1) == "#")
                //    LiteralPassword.Text = umbraco.library.GetDictionaryItem(value.Substring(1, value.Length - 1));
                //else
                    LiteralPassword.Text = value;
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //Response.Write(BlogProvider.Provider.GetBlogById(0).Title);
            if (!IsPostBack)
            {
                //Response.Write(Request.Cookies["sid"].Value);
                if (Request.QueryString["noredirect"] != "1")
                {
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["redirecturl"]))
                    {
                        if (MemberProvider.Provider.GetCurrentMember() != null)
                        {

                            if (Request.Cookies["sid"] != null && Request.Cookies["sid"] != null)
                            {
                                string redirectUrl = HttpContext.Current.Request.QueryString["redirecturl"];

                                Response.Redirect(redirectUrl);
                            }
                        }
                        else
                        {
                            //Classes.MemberManagement.ClearMemberCookiesAndSession(Response, Session);

                            // This code will never run anyway due to parent if statement?
                            //if (Member.GetCurrentMember() != null)
                            //{
                            //    Member.ClearMemberFromClient(Member.GetCurrentMember().Id);
                            //}
                            Session.Abandon();
                        }
                    }
                }
            }


            //signoutText.Text = SignOutLinkText;
            if (LogOutOnly)
            {
                PanelSignIn.Visible = false;
                if (MemberProvider.Provider.GetCurrentMember() != null)
                {
                    updateUserName();
                    PanelSignOut.Visible = true;
                }
                else
                    PanelSignOut.Visible = false;
            }
            else
            {
                if (MemberProvider.Provider.GetCurrentMember() != null)
                {
                    updateUserName();
                    PanelSignIn.Visible = false;
                    PanelSignOut.Visible = true;
                }
                else
                {
                    PanelSignIn.Visible = true;
                    PanelSignOut.Visible = false;
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the ButtonLogin control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonLogin_Click(object sender, EventArgs e)
        {
            _userError.Visible = false;
            if (Page.IsValid)
            {
                Member member = MemberProvider.Provider.LoginMember(TextBoxUserName.Text, TextBoxPassword.Text);
                if (member == null)
                {
                    _userError.Text = "There was an error with your login details please try again.";
                    _userError.Visible = true;
                    return;
                }
                if (!string.IsNullOrEmpty(Request.QueryString["redirectUrl"]))
                    Response.Redirect(Request.QueryString["redirectUrl"]);
                Response.Redirect(member.MemberUrl);
            }
        }

        private void updateUserName()
        {
            //LiteralLogout.Text = LoggedInText.Replace("%%NAME%%", Member.GetCurrentMember().Text);
        }

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion
    }
}